/*
 *     Android基础开发个人积累、沉淀、封装、整理共通
 *     Copyright (c) 2016. 曾繁添 <zftlive@163.com>
 *     Github：https://github.com/zengfantian || http://git.oschina.net/zftlive
 *
 *     Licensed under the Apache License, Version 2.0 (the "License");
 *     you may not use this file except in compliance with the License.
 *     You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 */

package com.vipyinzhiwei.android.sample.db;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.vipyinzhiwei.android.R;
import com.vipyinzhiwei.android.library.Alert;
import com.vipyinzhiwei.android.library.base.adapter.BaseMAdapter;
import com.vipyinzhiwei.android.library.base.ui.CommonActivity;
import com.vipyinzhiwei.android.library.tools.ToolString;
import com.vipyinzhiwei.android.sample.db.entity.User;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据库操作示例
 *
 * @author 曾繁添
 * @version 1.0
 */
public class DBDemoActivity extends CommonActivity {

    private EditText et_username, et_email, et_u_username, et_u_email;
    private Button btn_add, btn_update, btn_first_page, btn_per_page, btn_next_page, btn_end_page;
    private ListView lv_userlist;
    private UserListAdapter mUserListAdapter;
    private User selectItem = null;

    @Override
    public int bindLayout() {
        return R.layout.activity_db_demo;
    }

    @Override
    public void initParams(Bundle parms) {

    }

    @SuppressLint("NewApi")
    @Override
    public void initView(View view) {
        et_username = (EditText) findViewById(R.id.et_username);
        et_email = (EditText) findViewById(R.id.et_email);
        et_u_username = (EditText) findViewById(R.id.et_u_username);
        et_u_email = (EditText) findViewById(R.id.et_u_email);

        btn_add = (Button) findViewById(R.id.btn_add);
        btn_update = (Button) findViewById(R.id.btn_update);

        btn_first_page = (Button) findViewById(R.id.btn_first_page);
        btn_per_page = (Button) findViewById(R.id.btn_per_page);
        btn_next_page = (Button) findViewById(R.id.btn_next_page);
        btn_end_page = (Button) findViewById(R.id.btn_end_page);

        lv_userlist = (ListView) findViewById(R.id.lv_userlist);

        //初始化带返回按钮的标题栏
        String strCenterTitle = getResources().getString(R.string.DBDemoActivity);
//      ActionBarManager.initBackTitle(getContext(), getActionBar(), strCenterTitle);
        mWindowTitle.initBackTitleBar(strCenterTitle);
    }

    @Override
    public void doBusiness(Context mContext) {
        SQLiteDatabase db = LitePal.getDatabase();

        //设置列表适配器
        mUserListAdapter = new UserListAdapter(mContext);
        lv_userlist.setAdapter(mUserListAdapter);
        lv_userlist.setOnItemClickListener(mUserListItemClickListener);

        //设置添加数据按钮监听器
        btn_add.setOnClickListener(mAddUserClickListener);

        //设置修改按钮点击监听器
        btn_update.setOnClickListener(mUpdateUserClickListener);

        //查询用户
        queryUserList();
    }

    /**
     * 查询用户
     */
    private void queryUserList() {
        //先清除数据
        mUserListAdapter.clear();
        List<User> userList = LitePal.findAll(User.class);
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            user.setOrderNo(String.valueOf(i + 1));
            mUserListAdapter.addItem(user);
        }
        //通知数据改变
        mUserListAdapter.notifyDataSetChanged();
    }

    /**
     * 请求翻页
     *
     * @param pageNo 页码
     * @return 指定页数据集合
     */
    public List<User> requestPage(int pageNo) {
        List<User> result = new ArrayList<User>();


        return result;
    }

    /**
     * 添加用户按钮点击事件监听器
     */
    public View.OnClickListener mAddUserClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String username = et_username.getText().toString();
            String email = et_email.getText().toString();
            if (!ToolString.isNoBlankAndNoNull(username) || !ToolString.isNoBlankAndNoNull
                    (email)) {
                Alert.toastShort(getContext(), "请输入用户名和邮箱");
                return;
            }

            User user = new User();
            user.setUsername(username);
            user.setEmail(email);
            user.save();

            Alert.toastShort(getContext(), "添加成功");

            //刷新列表
            queryUserList();

            //清空添加框
            et_username.setText("");
            et_email.setText("");

        }
    };


    /**
     * 修改用户按钮点击事件监听器
     */
    public View.OnClickListener mUpdateUserClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String username = et_u_username.getText().toString();
            String email = et_u_email.getText().toString();
            if (!ToolString.isNoBlankAndNoNull(username) || !ToolString.isNoBlankAndNoNull
                    (email)) {
                Alert.toastShort(getContext(), "请输入更新用户名和邮箱");
                return;
            }

            if (null != selectItem) {
                //组装实体
                selectItem.setUsername(username);
                selectItem.setEmail(email);
                selectItem.update(selectItem.getId());
                Alert.toastShort(getContext(), "修改成功");

                //刷新列表
                queryUserList();

            } else {
                Alert.toastShort(getContext(), "没有选择用户");
            }
        }
    };

    /**
     * 用户列表点击事件监听器
     */
    private AdapterView.OnItemClickListener mUserListItemClickListener = new AdapterView
            .OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //获取点击的Item TODO
            User item = (User) mUserListAdapter.getItem(position);
            et_u_username.setText(item.getUsername());
            et_u_email.setText(item.getEmail());
        }
    };

    /**
     * 用户列表适配器
     */
    public class UserListAdapter extends BaseMAdapter {

        public UserListAdapter(Context mContext) {
            super(mContext);
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {

            Holder holder = null;
            // 查找控件
            if (null == convertView) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout
                        .activity_db_demo_listview_item, null);
                holder = new Holder();
                holder.tv_order_no = (TextView) convertView.findViewById(R.id.tv_order_no);
                holder.tv_username = (TextView) convertView.findViewById(R.id.tv_username);
                holder.tv_email = (TextView) convertView.findViewById(R.id.tv_email);
                holder.btn_update = (Button) convertView.findViewById(R.id.btn_update);
                holder.btn_del = (Button) convertView.findViewById(R.id.btn_del);

                // 缓存Holder
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }

            // 设置数据 TODO
            final User rowData = (User) getItem(position);
            holder.tv_order_no.setText(rowData.getOrderNo());
            holder.tv_username.setText(rowData.getUsername());
            holder.tv_email.setText(rowData.getEmail());
            holder.btn_update.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectItem = rowData;
                    et_u_username.setText(rowData.getUsername());
                    et_u_email.setText(rowData.getEmail());
                }
            });

            holder.btn_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Alert.dialog(getContext(), "删除确认", "确定要删除吗?",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mUserListAdapter.removeItem(position);
                                    mUserListAdapter.notifyDataSetChanged();

                                    if (LitePal.delete(User.class, rowData.getId()) > 0) {
                                        Alert.toastShort(getContext(), "删除成功");
                                    } else {
                                        Alert.toastShort(getContext(), "删除失败，原因：");
                                    }
                                }
                            },
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }
                    );
                }
            });

            return convertView;
        }

        public class Holder {
            TextView tv_order_no;
            TextView tv_username;
            TextView tv_email;
            Button btn_update;
            Button btn_del;
        }
    }

}
